﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVCSoict.Models.Authentication
{
    public class Author
    {
        public static bool Authorize(string username, string actionname)
        {
            bool res = false;
            try
            {
                using (var context = new staffsoictEntities1())
                {
                    var roleUsers = from u in context.Users
                                    where (u.username.Equals(username))
                                    select u.Roles.ToList();

                    var roleActions = from a in context.Actions
                                      where (a.name.Contains(actionname))
                                      select a.Roles;

                    foreach (var listRoleU in roleUsers.ToList())
                    {
                        foreach (var roleU in listRoleU)
                        {
                            foreach (var listRoleA in roleActions.ToList())
                            {
                                foreach (var roleA in listRoleA)
                                {
                                    if (roleU.id.Equals(roleA.id))
                                    {
                                        res = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                res = false;
            }
            if (res)
            {
                ViewBag.Deny = false;
            }
            else
            {
                ViewBag.Deny = true;
            }
            return res;
        }
    }
}